package com.cqq.print.business.controller.account;

import java.io.UnsupportedEncodingException;
import java.net.URLDecoder;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;

import com.alibaba.druid.util.StringUtils;
import com.alibaba.fastjson.JSONObject;
import com.cqq.base.filter.FMContext;
import com.cqq.common.core.base.BaseController;
import com.cqq.common.core.bean.PageInfoBean;
import com.cqq.print.base.service.PProducePlanService;
import com.cqq.print.base.service.PPublisherService;
import com.cqq.print.base.service.bean.PProducePlanBean;
import com.cqq.print.base.service.bean.PPublisherBean;
import com.cqq.print.business.service.PAccountDetailService;
import com.cqq.print.business.service.PAccountService;
import com.cqq.print.business.service.POrderService;
import com.cqq.print.business.service.PProduceDetailService;
import com.cqq.print.business.service.PProduceService;
import com.cqq.print.business.service.bean.PAccountBean;
import com.cqq.print.business.service.bean.PAccountDetailBean;
import com.cqq.print.business.service.bean.POrderBean;
import com.cqq.print.business.service.bean.PProduceBean;
import com.cqq.print.business.service.bean.PProduceDetailBean;
import com.cqq.print.constant.Constant;
import com.cqq.print.constant.PAccountStatus;
import com.cqq.pro.util.DateUtil;
import com.cqq.pro.util.ResponseUtil;

/**
 * 2015/06/25
 *
 * @author chenqq
 */
@Controller(value = "accountController")
@RequestMapping(value = { "account" }, method = {
		RequestMethod.POST,
		RequestMethod.GET })
public class AccountController extends BaseController{
	@Autowired
	private PAccountService pAccountService;
	@Autowired
	private PAccountDetailService pAccountDetailService;
	@Autowired
	private POrderService pOrderService;
	@Autowired
	private PPublisherService pPublisherService;
	@Autowired
	private PProduceService pProduceService;
	@Autowired
	private PProducePlanService pProducePlanService;
	@Autowired
	private PProduceDetailService pProduceDetailService;
	
	@RequestMapping(value = { "list" }, method = {
			RequestMethod.GET,
			RequestMethod.POST })
	public String toList(HttpServletRequest request, ModelMap out){

		return "account/accountmanager";
		
	}
	
	@RequestMapping(value = { "listAjax" }, method = {
			RequestMethod.GET,
			RequestMethod.POST })
	public String toListAjax(HttpServletRequest request, ModelMap out) throws UnsupportedEncodingException{

		String pubName = request.getParameter("pubName");		
		String currentPage = request.getParameter("currentPage");
		String pageSize = request.getParameter("pageSize");
		String startDate = request.getParameter("startDate");
		String endDate = request.getParameter("endDate");
		Map<String,Object> map = new HashMap<String, Object>();
		
		if(pubName!=null&&!pubName.trim().equals("")){
			pubName = URLDecoder.decode(pubName, "utf-8");
			map.put("pubName", pubName);
		}
		if(currentPage==null||currentPage.trim().length()<1){
			currentPage = "1";
		}
		if(pageSize==null||pageSize.trim().length()<1){
			pageSize = "20";
		}
		
		if(startDate==null||StringUtils.isEmpty(startDate))
		    startDate = DateUtil.formatDate(DateUtil.getFirstDateOfCurrentMonth());
		if(endDate==null||StringUtils.isEmpty(endDate))
			endDate = DateUtil.getCurrDateAfterAddDays(1);
		else
			endDate = DateUtil.addDaysForDate(endDate,1);
		
		map.put("startDate", startDate+" 00:00:00");
		map.put("endDate", endDate+" 00:00:00");
		
		int offset = (Integer.parseInt(currentPage) - 1) * Integer.parseInt(pageSize);
		map.put("orderClause", "create_date desc");
		map.put("pageSize", Integer.parseInt(pageSize));
		map.put("offset", offset);
		
		PageInfoBean<PAccountBean> page = pAccountService.queryPageAccounts(map);
		page.setPageNo(Integer.parseInt(currentPage));
		page.setPageSize(Integer.parseInt(pageSize));
		out.put("page", page);
		
		return "account/accountmanager";
		
	}
	
	@RequestMapping("toAddAccount")
	public String toAddAccount(Integer orderId, ModelMap out) throws UnsupportedEncodingException {
		try{
			if(orderId!=null){
				POrderBean poBean = pOrderService.queryOrderById(orderId);
				PPublisherBean ppubBean = pPublisherService.queryById(poBean.getPubId());
				List<PProducePlanBean> listPlanBean = pProducePlanService.queryByType(poBean.getOrderType());
				//if(poBean.getOrderType()==OrderType.ORDERTYPE_PRODUCE){
				PProduceBean pproBean = pProduceService.queryProduceByOrderNum(poBean.getOrderNum());
				List<PProduceDetailBean> listPPDetailBean = pProduceDetailService.queryDetailsWithProPlanByProduceId(pproBean.getId());
				out.put("listPPDetailBean", listPPDetailBean);
				//}
				
				out.put("poBean", poBean);
				out.put("listPlanBean", listPlanBean);
				out.put("ppubBean", ppubBean);
			}
		}catch(Exception e){
			log.error("程序异常",e);
		}
		return "account/addAccount";
	}
	
	/**
	 * <h3>核算</h3>
	 * 1、保存核算内容
	 * 2、更新订单状态：已核算
	 * @param paBean
	 * @param request
	 * @param response
	 * @throws UnsupportedEncodingException
	 */
	@RequestMapping("submitPAccount")
	public void submitPAccount(PAccountBean paBean,HttpServletRequest request,HttpServletResponse response) throws UnsupportedEncodingException {
		JSONObject json = new JSONObject();
		try{
			Date currDate = new Date();
			paBean.setCreateDate(currDate);
			paBean.setUpdateDate(currDate);
			paBean.setStatus(PAccountStatus.STATUS_WAITING_FOR_BILL);
			paBean.setCreateId(FMContext.getLoginUser().getId());
			List<PAccountDetailBean> listPADBean = new ArrayList<PAccountDetailBean>();
			for (int i=0;i<paBean.getProPlanId().length;i++) {
				PAccountDetailBean padBean = new PAccountDetailBean();
				padBean.setProPlanId(paBean.getProPlanId()[i]);
				padBean.setCount(paBean.getCount()[i]);
				padBean.setPrice(paBean.getPrice()[i]);
				padBean.setSumNoDiscountMoney(paBean.getSumNoDiscountMoney()[i]);
				padBean.setSumMoney(paBean.getSumMoney()[i]);
				padBean.setDiscount(paBean.getDiscount()[i]);
				listPADBean.add(padBean);
			}
			paBean.setListPAD(listPADBean);
			POrderBean orderBean = pOrderService.queryOrderByorderNum(paBean.getOrderNum());
			pAccountService.saveAccount(paBean);
			orderBean.setStatus(Constant.ORDER_STATUS_ACCOUNT);
			pOrderService.updateStatus(orderBean);
			json.put("result", "success");
		}catch(Exception e){
			json.put("result", "faild");
			json.put("msg", "程序异常，请联系运维人员！");
			log.error(e.getMessage());
		}
		
		ResponseUtil.outJsonString(response, json);
	}
	
	@RequestMapping("updateStatus")
	public void updateStatus(Integer paId,Integer status,HttpServletResponse response) throws UnsupportedEncodingException {
		JSONObject json = new JSONObject();
		try{
			Date currDate = new Date();
			PAccountBean paBean = new PAccountBean();
			paBean.setId(paId);
			paBean.setUpdateDate(currDate);
			if(status==PAccountStatus.STATUS_WAITING_FOR_CHECK)
				paBean.setStatus(PAccountStatus.STATUS_WAITING_FOR_CHECK);
			else if(status==PAccountStatus.STATUS_WAITING_FOR_MONEY)
				paBean.setStatus(PAccountStatus.STATUS_WAITING_FOR_MONEY);
			else if(status==PAccountStatus.STATUS_WAITING_FOR_FILE)
				paBean.setStatus(PAccountStatus.STATUS_WAITING_FOR_FILE);
			else if(status==PAccountStatus.STATUS_FILED)
				paBean.setStatus(PAccountStatus.STATUS_FILED);
			else
				paBean.setStatus(PAccountStatus.STATUS_WAITING_FOR_BILL);
			pAccountService.updateStatus(paBean);
			json.put("result", "success");
		}catch(Exception e){
			json.put("result", "faild");
			json.put("msg", "程序异常，请联系运维人员！");
			log.error(e.getMessage());
		}
		
		ResponseUtil.outJsonString(response, json);
	}
	
	@RequestMapping("toGetAccountDetail")
	public String toGetAccountDetail(HttpServletRequest request, ModelMap out) throws UnsupportedEncodingException {
		try{
		String proId = request.getParameter("proId");
			if(proId!=null&&proId.trim().length()>0){
				PAccountBean pABean = pAccountService.findById(Integer.parseInt(proId));
				List<PAccountDetailBean> listPADetailBean = pAccountDetailService.findDetailsByAccountId(Integer.parseInt(proId));
				out.put("pABean",pABean);
				out.put("listPADetailBean", listPADetailBean);
			}
		}catch(Exception e){
			log.error("程序异常",e);
		}
		return "account/accountDetail";
	}
	
}
